<?php
/**
 * excel导入错误日志导出
 * User: cxm
 * Date: 2020/2/10
 * Time: 9:50
 */
namespace App\Excel;

use EasyWeChat\Kernel\Support\Collection;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Events\AfterSheet;
use Maatwebsite\Excel\Concerns\WithEvents;

class ImportQuestionErrorExport implements FromCollection,WithEvents
{
    /**
     * 导出数据
     * @var array
     */
    protected $data=array();

    public function __construct($data){
        $this->data = $data;
    }

    /**
     * registerEvents.
     * 事件监听
     * @return array
     */
    public function registerEvents(): array
    {
        return [
            // 生成表单元后处理事件
            AfterSheet::class => function (AfterSheet $event) {
                // 定义列宽度
                $widths = ['A' => 20, 'B' => 15, 'C' => 10, 'D' => 12, 'E' => 14, 'F' => 14, 'G' => 20, 'H' => 25, 'I' => 16, 'J' => 20, 'K' => 10, 'L' => 20];
                foreach ($widths as $k => $v) {
                    // 设置列宽度
                    $event->sheet->getDelegate()->getColumnDimension($k)->setWidth($v);
                }
            }
        ];
    }

    //数组转集合
    public function collection()
    {
        return new Collection($this->createData());
    }

    //业务代码
    public function createData()
    {
        $data[] = ["导入标识","错误备注","题目","正确答案","选项A","选项B","选项C","选项D","选项E","选项F","选项G","选项H","选项I","选项J"];
        foreach ( $this->data as $key=>$item) {
            $new_arr = [$item['lot'],$item['msg']];
            $excel_date = $item['excel_data'];
            $data[] = array_merge($new_arr,$excel_date);
        }
        return $data;
    }
}